package org.example.demo1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class demo2 {
    public static void main(String[] args) {
        Tickets2 tickets2 = new Tickets2();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                tickets2.sell();
            }
        },"我").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                tickets2.sell();
            }
        },"你").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                tickets2.sell();
            }
        },"它").start();

    }
}

class Tickets2{
    private int ticketNums = 50;
    Lock lock = new ReentrantLock();

   public  void sell(){


           try{
               lock.lock();
               if (ticketNums > 0){
               System.out.println(Thread.currentThread().getName()+"卖出了第"+ticketNums--+"张票,剩余"+ticketNums+"张票");
               }
           }catch (Exception  e){
               e.printStackTrace();
           }finally{
               lock.unlock();
           }

    }
}
